import { Component } from 'react'
import PT from 'prop-types'

class DemoTwo extends Component {
    /* 属性规则校验 */
    static defaultProps = {
        x: 0,
        y: false
    }
    static propTypes = {
        title: PT.string.isRequired,
        x: PT.oneOfType([PT.number, PT.string]),
        y: PT.bool
    }

    /* 初始化状态 */
    state = {
        num: this.props.x, //10
        count: 0
    }

    render() {
        console.log('render')
        let { title } = this.props,
            { num, count } = this.state
        return <div className="box">
            {title} && {num} && {count}
            <br />
            <button onClick={() => {
                /* this.state.num++ //这样操作，仅仅是立即修改了状态值，但是视图不会更新
                console.log(this.state.num) */

                /* // 只有基于特点的方法 setState 修改状态，才可以保证，状态更新的同时，视图也会更新
                // Component.prototype.setState = function (partialState, callback) {...}
                // setState是支持部分状态更改的
                this.setState({
                    num: num + 1
                }, () => {
                    console.log('callback')
                }) */

                // 强制更新
                this.state.num++
                this.forceUpdate(()=>{
                    console.log('forceUpdate callback')
                })
            }}>修改NUM</button>

            <br />
            <button>修改COUNT</button>
        </div>
    }

    shouldComponentUpdate(nextProps, nextState) {
        console.log('shouldComponentUpdate', nextState, this.state)
        return true
    }

    UNSAFE_componentWillUpdate() {
        console.log('componentWillUpdate', this.state)
    }

    componentDidUpdate() {
        console.log('componentDidUpdate')
    }
}

export default DemoTwo